import traceback
from django.core.paginator import Paginator, EmptyPage
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.hashers import make_password
from django.db.models import Q


class User(AbstractUser):
    id = models.BigAutoField(primary_key=True)

    # 用户类型： 1 超管 | 1000 普通管理员 | 2000 学生 | 3000 老师
    usertype = models.PositiveIntegerField(choices=[(1, '超管'), (1000, '普通管理员'), (2000, '学生'), (3000, '老师')],
                                           verbose_name="用户类型")
    realname = models.CharField(max_length=30, db_index=True, verbose_name="真实姓名")
    studentno = models.CharField(max_length=10, db_index=True, null=True, blank=True, verbose_name="学号")
    desc = models.CharField(max_length=500, null=True, blank=True)

    REQUIRED_FIELDS = ['usertype', 'realname']

    class Meta:
        db_table = "CIMP_user"
        verbose_name = "用户信息"
        verbose_name_plural = verbose_name

    # 将增加与列出用户的操作设为静态方法
    @staticmethod
    def addone(data):
        try:
            user = User.objects.create(
                username=data['username'],
                password=make_password(data['password']),
                usertype=data['usertype'],
                realname=data['realname'],
                studentno=data['studentno'],
                desc=data['desc']
            )
            return {'ret': 0, 'id': user.id}
        except:
            err = traceback.format_exc()
            return {'ret': 2, 'msg': err}

    # 将列出用户设置为静态方法
    @staticmethod
    def listbypage(pagenum, pagesize, keywords):
        try:
            qs = User.objects.values("id", "username", "realname", "studentno", "desc", "usertype") \
                .order_by('-id')
            # 查看是否有 关键字 搜索 参数
            if keywords:
                conditions = [Q(realname__contains=one) for one in keywords.split(' ') if one]
                query = Q()
                for condition in conditions:
                    query &= condition
                qs = qs.filter(query)

            # 使用分页对象，设定每页多少条记录
            pgnt = Paginator(qs, pagesize)

            # 从数据库中读取数据，指定读取其中第几页
            page = pgnt.page(pagenum)

            # 将 QuerySet 对象 转化为 list 类型
            retlist = list(page)

            # total指定了 一共有多少数据
            return {'ret': 0, 'items': retlist, 'total': pgnt.count, "keywords": keywords}

        except EmptyPage:
            return {'ret': 0, 'items': [], 'total': 0, "keywords": keywords}

        except:
            return {'ret': 2, 'msg': f'未知错误\n{traceback.format_exc()}'}

    # 将修改用户信息设置为静态方法
    @staticmethod
    def modifyone(oid, newdata):
        try:
            user = User.objects.get(id=oid)
            if 'username' in newdata:
                username = newdata['username']
                if User.objects.filter(username=username).exists():
                    return {'ret': 3, 'msg': f'登入名为{username}的用户已存在！'}
            if 'password' in newdata:
                user.password = make_password(newdata.pop('password'))
            # setattr(x,y,z) : x.y=z
            for field, value in newdata.items():
                setattr(user, field, value)
            user.save()
            return {'ret': 0}
        except User.DoesNotExist:
            return {'ret': 1, 'msg': f'id为{oid}的用户不存在！'}
        except:
            # 输出错误信息
            err = traceback.format_exc()
            return {'ret': 2, 'msg': err}

    @staticmethod
    def deleteone(oid):
        try:
            user = User.objects.get(id=oid)
            # 调用 queryset.delete()
            user.delete()
            return {'ret': 0}
        except User.DoesNotExist:
            return {'ret': 1, 'msg': f'id为{oid}的用户不存在！'}
        except:
            err = traceback.format_exc()
            return {'ret': 2, 'msg': err}
# 定义统一响应接口
